package edu.ycu.aladdin.collector;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @since 2018-12-11 7:18 PM
 */
public class DataForamat {

    static String jsonRate = DataForamat.class.getClassLoader().getResource("data/rate/rate.json").getFile();

    static String csvRate = DataForamat.class.getClassLoader().getResource("data/rate/").getFile() + "rate.csv";

    static {
        try {
            File csvRateFile = new File(csvRate);
            if (!csvRateFile.exists()){
                csvRateFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void formatRate() throws IOException {

        File jsonFile = new File(jsonRate);
        String json = FileUtils.readFileToString(jsonFile);
        JSONObject object = JSON.parseObject(json);

        JSONArray time = object.getJSONArray("t");
        JSONArray close = object.getJSONArray("c");
        JSONArray open = object.getJSONArray("o");
        JSONArray low = object.getJSONArray("l");
        JSONArray hight = object.getJSONArray("h");

        StringBuilder builder = new StringBuilder();
        int len = time.size();
        for (int i = 0; i < len; i++) {
            String times = time.getString(i);

            builder.append(timeStamp2Date(times,"yyyy-MM-dd") + "," + close.getString(i) + "," + open.getString(i) + "," + low.getString(i) + "," + hight.getString(i) + "\n");
        }

        FileUtils.writeStringToFile(new File(csvRate),builder.toString());
        System.out.println(builder.toString());
    }

    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.equals("null")) {
            return "";
        }
        if (format == null) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }
}
